﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;

namespace SJ.Platform.File.DBOperation
{
    public class MongoOperation
    {
        private readonly GridFSBucket _bucket;

        public MongoOperation(IMongoDatabase mongoDatabase)
        {
            // 创建GridFS存储桶
            _bucket = new GridFSBucket(mongoDatabase);
        }

        /// <summary>
        /// 文件保存
        /// </summary>
        /// <param name="fileName">文件名称，为了避免重复建议使用文件的ID和文件名称作为文件名称，如：ID_XXX.docx</param>
        /// <param name="bytes">文件的字节流</param>
        /// <returns></returns>
        public async Task<string> Save(string fileName, byte[] bytes)
        {
            try
            {
                var id = await _bucket.UploadFromBytesAsync(fileName, bytes);
                return id.ToString();
            }
           catch(Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="id">文件保存成功时返回的ID</param>
        /// <returns></returns>
        public async Task<byte[]> DownLoad(string id)
        {
            ObjectId objId = new ObjectId(id);
            return await _bucket.DownloadAsBytesAsync(objId);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Delete(string id)
        {
            try
            {
                ObjectId objId = new ObjectId(id);
                await _bucket.DeleteAsync(objId);
                return true;
            }
            catch(Exception e)
            {
                return false;
            }
        }
    }
}
